<?php

// @author 3ogx <3ogx.com@gmail.com>

namespace Jushuitan;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;

class Client extends ErpBase
{
    use ErpHelpTrait;
    public function sendRequest($url, array $data)
    {
        $client = new HttpClient(['base_uri' => $url]);

        // 同步
        // $params['form_params'] = $data;
        // $params['headers']     = ['Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'];
        // $response              = $client->request('POST', $url, $params);
        // $ret                   = json_decode($response->getBody(), true);
        // if ($ret['code'] === 0) {
        //     return $ret;
        // }
        // throw new ErpException(sprintf('请求失败！错误信息：%s, 错误编码： %s', $ret['msg'], $ret['code']));

        // 异步
        $params['form_params'] = $data;
        $params['headers']     = ['Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'];
        $request               = $client->postAsync($url, $params);
        $promise               = $request->then(function (ResponseInterface $request) {
            $contents = $request->getBody()->getContents();

            return json_decode($contents, true);
        }, function (RequestException $e) {
            return json_decode(json_encode($e, true));
        });


        return $this->object_2_array($promise->wait());
    }
}
